<template>
    <!-- 资讯管理 -->
    <div class="scheme">
        <div class="header-box">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="类型：">
                    <el-select v-model="formInline.type_id" placeholder="请选择" clearable>
                        <el-option label="全部" value=""></el-option>
                        <el-option :label="item.name" :value="item.id" v-for="item in typeList"
                                   :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题搜索：">
                    <el-input v-model="formInline.name" placeholder="请输入搜索商品名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="submitForm">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" icon="el-icon-plus" @click="addArticle">新增</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="tables">
            <el-table border :data="tableData" max-height="650" highlight-current-row :row-style="{height: '20px'}"
                      :header-cell-style="{background:'#e6e6e6',color:'#000000'}">
                <el-table-column prop="id" align="center" label="ID" width="60"></el-table-column>
                <el-table-column prop="name" align="center" label="名称"></el-table-column>
                <el-table-column prop="status" align="center" label="状态" width="80">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'"
                                disable-transitions>{{ scope.row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="image" align="center" label="图片">
                    <template slot-scope="scope">
                        <img style="width: 80px;height: 50px;display: block;margin: 0 auto;" :src="scope.row.image"
                             alt="" srcset=""/>
                    </template>
                </el-table-column>
                <el-table-column prop="is_top" align="center" label="是否头条" width="80">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.is_top === 1 ? 'success' : 'danger'"
                                disable-transitions>{{ scope.row.is_top === 1 ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" align="center" label="创建时间"></el-table-column>
                <el-table-column prop="created_at" align="center" label="修改时间"></el-table-column>

                <el-table-column align="center" label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button size="mini" type="success" plain icon="el-icon-edit" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>

                        <el-button size="mini" type="danger" plain icon="el-icon-delete"
                                   @click="handleDelete(scope.row)">删除
                        </el-button>
                        <!--                        <el-button size="mini" type="warning" plain @click="handleAddStock(scope.row)">-->
                        <!--                            新增库存-->
                        <!--                        </el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :current-page.sync="page" :page-sizes="[15, 20, 50, 100]" :page-size="limit"
                               layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 新增弹框 -->
        <el-dialog :title="title" :visible.sync="dialogAddArticle" width="60%">
            <el-form :model="form" label-width="100px" :rules="rules">
                <el-form-item label="标题:" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="类型:" prop="type_id">
                    <el-select v-model="form.type_id" placeholder="请选择" clearable>
                        <el-option :label="item.name" :value="item.id" v-for="item in typeList" :key="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态:" prop="status">
                    <el-radio-group v-model="form.status" size="medium">
                        <el-radio border label="1">启用</el-radio>
                        <el-radio border label="2">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="封面图:" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="form.image" :src="form.image" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="是否头条:" prop="is_top">
                    <el-radio-group v-model="form.is_top" size="medium">
                        <el-radio border label="1">是</el-radio>
                        <el-radio border label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="内容:" prop="content">
                    <quill-editor class="ql-editor" ref="myTextEditor" v-model="form.content" :options="editorOption"></quill-editor>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddArticle = false">取 消</el-button>
                <el-button type="primary" @click="submitArticleData">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import {quillEditor} from "vue-quill-editor";
import {quillRedefine} from "vue-quill-editor-upload";
// import imageResize  from 'quill-image-resize-module' // 调整大小组件。
// import { ImageDrop } from 'quill-image-drop-module'; // 拖动加载图片组件。
// quillEditor.register('modules/imageResize', imageResize)
// quillEditor.register('modules/imageDrop', ImageDrop)
export default {
    data() {
        return {
            formInline: {
                type_id: "",
                name: "",
            },
            form: {
                name: "",
                type_id: [],
                status: '',
                image: '',
                is_top: "",
                content: '',

            },
            typeList: [],
            editorOption: {
                placeholder: "请输入内容",
            },
            tableData: [],
            id: 0,
            dialogAddArticle: false, //默认新增框隐藏
            title: "新增 ", //默认新增
            isEdit: false, //默认为新增
            page: 1, //默认第一页
            limit: 15, //默认一页显示10条数据
            total: 0,

            uploadUrl: '',
            isUpload: false,//是否图片上传
            dialogVisible: false,

            infoForm: {nickname: '', mobile: ''},
            rules: {
                name: [{required: true, message: "请输入商品名称", trigger: "blur"}],
                type_id: [{required: true, message: "请选择类型", trigger: "blur"}],
                status: [{required: true, message: "请选择状态", trigger: "blur"}],
                is_top: [{required: true, message: "请选择是否头条", trigger: "blur"}],
                image: [{required: true, message: "请上传封面图", trigger: "blur"}],
                content: [{required: true, message: "请输入内容", trigger: "blur"}],
            },

        };
    },
    created() {
        this.getArticleTypeList();
        this.getArticleList();
        this.uploadUrl = this.$api.imageUpload;
        this.editorOption=quillRedefine({
            uploadConfig:{
                action:this.uploadUrl,
                name:'file',
                res:(response)=>{
                    return response.data.url;

                },
                placeholder: "请输入内容",

                // imageDrop: true, //图片拖拽
                // imageResize: { //放大缩小
                //     displayStyles: {
                //         backgroundColor: "black",
                //         border: "none",
                //         color: "white"
                //     }
                // }
            }

        });
    },
    activated() {
        this.getArticleTypeList();
        this.getArticleList();
    },
    components: {
        quillEditor,quillRedefine
    },
    methods: {
        handleAvatarSuccess(res, file) {
            this.form.image = URL.createObjectURL(file.raw);
            if (res.code == 200) {
                this.form.image = res.data.url;
                this.isUpload = true
            }

        },
        beforeAvatarUpload(file) {
            const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 jpeg、png或者gif格式!');
            }
            if (!isLt10M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt10M;
        },
        initForm() {
            this.form.name = "";
            this.form.type_id = [];
            this.form.status = '';
            this.form.image = '';
            this.form.is_top = "";
            this.form.content = '';
        },
        // 点击新增按钮
        addArticle() {
            this.title = "新增资讯";
            this.dialogAddArticle = true;
            this.isEdit = false;
            this.initForm();

        },
        getArticleTypeList(page, limit) {
            let params = {
                per_page: 1000,
                status: 1,
            };
            this.$get(this.$api.articleTypeApi, params).then((res) => {
                if (res.code == 200) {
                    this.typeList = res.data.data;
                    this.total = res.data.total;
                } else {
                    return this.$message.error(res.msg);
                }
            });
        },
        getArticleList(page, limit) {
            let params = {
                page: this.page,
                per_page: this.limit,
                type_id: this.formInline.type_id,
                name: this.formInline.name,
            };
            this.$get(this.$api.articleApi, params).then((res) => {
                if (res.code == 200) {
                    this.tableData = res.data.data;
                    this.total = res.data.total;
                } else {
                    return this.$message.error(res.msg);
                }
            });
        },
        forEachFun(str) {
            let ids = [];
            if (str.length > 0) {
                ids = str.split(",");
                ids.forEach((item, index) => {
                    ids[index] = parseInt(ids[index])

                });
            }
            return ids;

        },
        // 点击编辑按钮
        handleEdit(row) {
            this.title = "编辑";
            this.id = row.id;
            this.form.name = row.name;
            this.form.type_id = row.type_id;
            this.form.status = row.status.toString();
            this.form.image = row.image;
            this.form.is_top = row.is_top.toString();
            this.form.content = row.content;
            this.dialogAddArticle = true;
            this.isEdit = true;
        },
        // 点击编辑弹框取消按钮
        goToEdit() {
            this.dialogAddArticle = false;
            this.isEdit = false;
        },

        // 点击删除按钮
        handleDelete(row) {
            this.$confirm("此操作将永久删除此条数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$delete(this.$api.articleApi + "/" + row.id).then((res) => {
                        if (res.code == 200) {
                            this.getArticleList(this.page, this.limit);
                            return this.$message.success("删除成功！");
                        } else {
                            return this.$message.error(res.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        handleAddStock(row) {
            this.dialogStock = true;
            this.stockForm.num = '';
            this.stockForm.name = row.name;
            this.stockForm.stock_num = row.stock_num;
            this.goods_id = row.id;


        },
        // 分页
        handleSizeChange(size) {
            this.limit = size;
            this.getArticleList();
        },
        handleCurrentChange(index) {
            this.page = index;
            this.getArticleList();
        },
        // 点击查询按钮
        submitForm() {
            this.getArticleList();
        },


        // 提交课程数据确定按钮
        submitArticleData() {
            if (this.form.name == "") {
                return this.$message.error("请输入标题！");
            }

            if (this.form.type_id == "") {
                return this.$message.error("请选择类型！");
            }
            if (this.form.status == "") {
                return this.$message.error("请选择状态！");
            }
            if (this.form.image == "") {
                return this.$message.error("请上传图片！");
            }
            if (this.form.is_top == "") {
                return this.$message.error("请选择是否头条！");
            }
            if (this.form.content == "") {
                return this.$message.error("请输入内容！");
            }


            let params = {
                name: this.form.name,
                type_id: this.form.type_id,
                status: this.form.status,
                image: this.form.image,
                is_top: this.form.is_top,
                content: this.form.content,
            };

            if (this.isEdit) {
                this.$put(this.$api.articleApi + "/" + this.id, params).then((res) => {
                    if (res.code == 200) {
                        this.form.status = false;
                        this.dialogAddArticle = false;
                        this.getArticleList(this.page, this.limit);
                        return this.$message.success("编辑成功！");
                    } else {
                        return this.$message.error(res.msg);
                    }
                });
            } else {
                this.$post(this.$api.articleApi, params).then((res) => {
                    if (res.code == 200) {
                        this.form.status = false;
                        this.dialogAddArticle = false;
                        this.getArticleList(this.page, this.limit);
                        return this.$message.success("新增成功！");
                    } else {
                        return this.$message.error(res.msg);
                    }
                });
            }
        },
        submitStockData() {
            if (this.stockForm.num == '' || this.stockForm.num <= 0) {
                return this.$message.error('请输入正确新增库存数');
            }
            this.$post(this.$api.goodsStockNumApi, {num: this.stockForm.num, id: this.goods_id}).then((res) => {
                if (res.code == 200) {
                    this.dialogStock = false;
                    this.getArticleList(this.page, this.limit);
                    return this.$message.success("新增成功！");
                } else {
                    return this.$message.error(res.msg);
                }
            });


        },
        handleImageRemove(file, fileList) {

            //移除图片
            this.form.images = fileList;
        },
        // 点击查看预览图片
        handleImagePreview(file) {
            //预览图片时调用
            this.dialogImageUrl = file.url;
            this.dialogImageVisible = true;
        },
        handleImageSuccess(res, file) {
            this.form.image = URL.createObjectURL(file.raw);
            if (res.code == 200) {
                this.form.images.push({url: res.data.url});
                this.isUpload = true
            }

        },
        beforeImageUpload(file) {
            const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
            console.log('file.type', file.type)
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 jpeg、png或者gif格式!');
            }
            if (!isLt10M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt10M;
        },
        //图片上传超过数量限制提示
        handleImageExceed(file, fileList) {
            this.$message.error('上传图片数量超过上限');
        },
        //图片上传失败调用
        imgUploadError(err, file, fileList) {
            this.$message.error('上传图片失败!');
        },
    },
};
</script>

<style scoped>
.pagination {
    text-align: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

/* el-upload 修改修改样式 */

.avatar {
    width: 100%;
    height: 100%;
    display: block;
}

.is-selected {
    color: #1989fa;
}
</style>
